package com.junqson.je.recruit.service;

import com.junqson.je.common.UserHolder;
import com.junqson.je.common.model.ApiResult;
import com.junqson.je.common.model.User;
import com.junqson.je.common.model.vo.SimpleUserInfo;
import com.junqson.je.common.util.AppUtil;
import com.junqson.je.recruit.model.JobModel;
import com.junqson.je.recruit.model.dto.JobDTO;
import com.junqson.je.recruit.model.vo.JobVo;
import com.junqson.je.recruit.repo.JobRepo;
import com.junqson.je.recruit.util.PageUtil;
import com.junqson.je.recruit.util.UserInfoCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Descriptions
 * @Company
 * @Author Junqson
 * @Date 2020/2/5 14:52
 * @Version 1.0
 */
@Slf4j
@Service
public class JobService {
    @Autowired
    JobRepo jobRepo;

    @Autowired
    UserInfoCache userInfoCache;

    public void publishJob(JobDTO jobDTO) {
        JobModel jobModel = new JobModel();
        // 职位相关信息
        AppUtil.copyPropertiesIgnoreNull(jobDTO, jobModel);
        User user = UserHolder.get();
        // 发布者基本信息
        jobModel.setPublisherId(user.getUserId());
        jobModel.setCompany(user.getCompany());
        jobModel.setPublishTime(new Date());

        jobRepo.save(jobModel);
        log.info("job create success, job id :{}, publisher id {}", jobModel.getJobId(), user.getUserId());
    }

    public ApiResult closeJob(int jobId) {
        // 检查权限
        JobModel jobModel = checkJobAuth(jobId);
        if (jobModel == null) {
            return ApiResult.error("职位不存在或无权修改");
        }
        jobModel.setClosed(true);
        jobRepo.save(jobModel);
        return ApiResult.success();
    }

    public JobVo getByJobId(Integer jobId) {
        JobModel model = jobRepo.findByJobId(jobId);
        return convertToJobVo(model);
    }

    public ApiResult updateJobInfo(JobDTO jobDTO) {
        // 检查权限
        int jobId = jobDTO.getJobId();
        JobModel jobModel = checkJobAuth(jobId);
        if (jobModel == null) {
            return ApiResult.error("职位不存在或无权修改");
        }
        if (jobModel.isClosed()) {
            return ApiResult.error("职位已关闭，不可修改");
        }
        AppUtil.copyPropertiesIgnoreNull(jobDTO, jobModel);
        // 更新发布时间
        jobModel.setPublishTime(new Date());
        jobRepo.save(jobModel);
        return ApiResult.success();
    }

    public List<JobVo> getJobByPublisherId(int userId) {
        List<JobModel> models = jobRepo.findByPublisherIdOrderByPublishTimeDesc(userId);
        return models.stream().map(this::convertToJobVo).collect(Collectors.toList());
    }

    public List<JobVo> getOpenJobByPublisherId(int userId) {
        List<JobModel> models = jobRepo.findByPublisherIdAndClosedFalseOrderByPublishTimeDesc(userId);
        return models.stream().map(this::convertToJobVo).collect(Collectors.toList());
    }


    public List<JobVo> pageAllJob(Integer page, Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "publishTime");
        Pageable pageable = PageUtil.getPageable(page, size, sort);
        Page<JobModel> jobs = jobRepo.findAllByClosedFalse(pageable);
        List<JobModel> models = jobs.getContent();
        return models.stream().map(this::convertToJobVo).collect(Collectors.toList());
    }

    public List<JobVo> pageJobBylocation(String location, Integer page, Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "publishTime");
        Pageable pageable = PageUtil.getPageable(page, size, sort);
        Page<JobModel> jobs = jobRepo.findByLocationAndClosedFalse(location, pageable);
        List<JobModel> models = jobs.getContent();
        return models.stream().map(this::convertToJobVo).collect(Collectors.toList());
    }

    public List<JobVo> pageJobByCategory(String category, Integer page, Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "publishTime");
        Pageable pageable = PageUtil.getPageable(page, size, sort);
        Page<JobModel> jobs = jobRepo.findByCategoryAndClosedFalse(category, pageable);
        List<JobModel> models = jobs.getContent();
        return models.stream().map(this::convertToJobVo).collect(Collectors.toList());
    }


    public List<JobVo> pageJobByLocationAndCategory(String location, String category, Integer page, Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "publishTime");
        Pageable pageable = PageUtil.getPageable(page, size, sort);
        Page<JobModel> jobs = jobRepo.findByLocationAndCategoryAndClosedFalse(location, category, pageable);
        List<JobModel> models = jobs.getContent();
        return models.stream().map(this::convertToJobVo).collect(Collectors.toList());
    }

    /**
     * 检查是否有修改此Job的权限，否则返回null
     *
     * @return
     */
    public JobModel checkJobAuth(int jobId) {
        JobModel job = jobRepo.findByJobId(jobId);
        if (job == null) {
            log.error("job not found, id {}", jobId);
            return null;
        }
        User user = UserHolder.get();
        int userId = user.getUserId();
        if (userId != job.getPublisherId()) {
            log.error("not auth modify job, userid: {}, jobid: {}", userId, jobId);
            return null;
        }
        return job;
    }

    public JobVo convertToJobVo(JobModel jobModel) {
        if (jobModel == null) {
            return null;
        }
        JobVo jobVo = new JobVo();
        AppUtil.copyPropertiesIgnoreNull(jobModel, jobVo);
        int publisherId = jobModel.getPublisherId();
        SimpleUserInfo userInfo = userInfoCache.getUserInfo(publisherId);
        jobVo.setPublisherInfo(userInfo);
        return jobVo;
    }
}
